<?php
class AuthFilter extends UE_Controller_Filter  {

	function __construct() {
		
	}
	
	public function before() {
		//return true;
		UE_Loader::loadModel('RoleModel', 'user');
		$userModel = new UserModel();
		
		if (empty($_SESSION['user_id']) && !empty($_COOKIE[cfg('auth_cookie_key')])) {
			$uid = $pass = '';						
			$authDe = UE_Crypt::decrypt($_COOKIE[cfg('auth_cookie_key')], md5(cfg('auth_key')));
			list($uid, $pass) = explode("\t", $authDe);
						
			$user = $userModel->read((float)$uid);
			
			if ($pass == $user['user_pass']) {
				// 设置session
				$userModel->setLoginInfo($user);
			} else {
				$userModel->logout();
			}
		}
		
		//*/
		// 把未初始化session的请求设为游客
		if(empty($_SESSION['user_name'])) {
			$_SESSION['ip']             = UE_IP::realIp();
			$_SESSION['user_id']        = 0;
			$_SESSION['user_type']      = 'special';
			$_SESSION['user_role']      = cfg('guest_role_id');
			$_SESSION['user_name']      = 'guest';
			$_SESSION['user_realname']  = 'guest';
		}
		
		//*
		// 权限控制		
		$app   = $_GET['app'];
		$ctl   = $_GET['ctl'];
		$act   = $_GET['act'];
		
		if(!AppModel::isActionAcessable($app, $ctl, $act, $httpCode)) {			
			if ($httpCode == 404) {		
				$_GET['app']   = 'user';
				$_GET['ctl']   = 'account';
				$_GET['act']   = 'message';			
				$_GET['id']    = 404;		
				$this->setErr('您访问的页面不存在');	
			} elseif ($httpCode == 401) {
				// 没有权限
				if (empty($_SESSION['user_id'])) {
					// 用户未登录
					$this->setErr('您没有权限进行该操作，请您先登录。');
					$_GET['app'] = 'user';
					$_GET['ctl'] = 'account';
					$_GET['act'] = 'login';
					$_GET['id']  = urlencode(UE::url());
				} else {
					// 用户已登录,禁止访问
					$relogUrl = UE_Url::make('user/account/logout/'.urlencode(UE_Url::make('user/account/login')));
					$this->setErr("您没有权限进行该操作。<a href=\"{$relogUrl}\">切换用户<a/>");
					$_GET['app'] = 'user';
					$_GET['ctl'] = 'account';
					$_GET['act'] = 'message';
					$_GET['id']  = $httpCode = 403;					
				}
			}
			
			cfg('send_http_status') && !IS_AJAX && setRspStatus($httpCode);
			
			if(IS_AJAX) {
				print json_encode(array('err'=>array('code'=>$httpCode, 'text'=> $this->getLastErr())));
				die;
			}			
			
			return false;
		}
			
		return true;
	}
	
	public function after() {
		
	}
}